import { getCategory, getCategoryData, getCategoryType } from '@/services';
import { CategoryDetails, CategoryList, CategoryType } from '@/types/modules/category';
import { Effect, Reducer } from 'umi';

export interface CategoryModelState {
  category:CategoryList[],
  categoryType:Partial<CategoryType>
  categoryData:CategoryDetails[]
}

export interface CategoryModelTypes {
  namespace: 'category';
  state: CategoryModelState;
  effects: {
    getCategory:Effect;
    getCategoryType:Effect;
    getCategoryData:Effect;
  };
  reducers: {
    save: Reducer<CategoryModelState>;
  };
}

const CategoryModel: CategoryModelTypes = {
  namespace: 'category',
  state: {
    category:[],
    categoryType:{},
    categoryData:[]
  },
  effects: {
    *getCategory({ payload }, { call, put }) {
      let result = yield call(getCategory,payload)      
      if (result.data) {
        yield put({
          type: 'save',
          payload: {
            category: result.data
          }
        })
      }
    },
    *getCategoryType({ payload }, { call, put }) {
      let result = yield call(getCategoryType,payload)      
      if (result.data) {
        yield put({
          type: 'save',
          payload: {
            categoryType: result.data
          }
        })
      }
    },
    *getCategoryData({ payload }, { call, put }) {
      let result = yield call(getCategoryData,payload)            
      if (result.data) {
        yield put({
          type: 'save',
          payload: {
            categoryData: result.data[0]
          }
        })
      }
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },

  }
};

export default CategoryModel;

